//
//  ZCScanErrorcorrectVC.m
//  zctx
//
//  Created by apple on 16/4/12.
//  Copyright © 2016年 sanliang. All rights reserved.
//

#import "ZCScanErrorcorrectVC.h"

#import "ZCRaiseCell.h"
#import "ZCRaisePicCell.h"
#import "ZCScanErrorCell.h"

#import "ZCSearchHeaderView.h"
#import "ZCLoginVC.h"

#import "ELCImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "FSMediaPicker.h"

typedef enum {
    RaiseReginTypeProvince = 100,
    RaiseReginTypeCity,
} RaiseReginType;

@interface ZCScanErrorcorrectVC ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate,UITextFieldDelegate,ZCRaiseCellDelegate,MessagePhotoViewDelegate,FSMediaPickerDelegate>{
    
    NSInteger imageCount;
    NSMutableArray *ImgArray;

}

@property (nonatomic, assign) NSInteger tableViewNum;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *viewFooter;
@property (nonatomic, strong) UIButton *footBtn;

@property (nonatomic,strong) NSDictionary *contentDict;


@property (nonatomic,strong)NSMutableArray *contentArray; //检测内容
@end

@implementation ZCScanErrorcorrectVC


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCRaiseVC"];
    [MTA trackPageViewBegin:@"ZCRaiseVC"];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCRaiseVC"];
    [MTA trackPageViewEnd:@"ZCRaiseVC"];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.tableView.shiftHeightAsDodgeViewForMLInputDodger = 44.0f+5.0f;
    [self.tableView registerAsDodgeViewForMLInputDodger];
}

-(void)viewDidLayoutSubviews {
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    imageCount = 0;
    ImgArray = [NSMutableArray arrayWithCapacity:0];
    self.contentDict = [[NSDictionary alloc]init];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
    });
    [self setNavigationItems];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#ebeded"];
    self.navigationItem.title = @"我要纠错";
    
    //添加tableview
    [self.view addSubview:self.tableView];
    
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0,0));
    }];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCScanErrorCell" bundle:nil] forCellReuseIdentifier:@"scanerror"];
    
}


-(void)delegateButton:(NSNotification *)nofi{
    NSIndexPath *index = [NSIndexPath indexPathForItem:5 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:index] withRowAnimation:UITableViewRowAnimationNone];
}


#pragma mark - button

-(void)setNavigationItems {
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
}

- (void)backButtonPressed{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tapGestureRecognizer {
    [self.view endEditing:YES];
}

#pragma mark - UITableView DataSource & Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section==0||section==1) {
        return 1;
    }else{
        return 3;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIndentity = @"Cell";
    ZCRaiseCell *cell;
    
    if (indexPath.section==0) {
        cell = [[ZCRaiseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity cellType:RaiseCellTypePush];
        cell.rightImgView.hidden = YES;
        cell.labelTitle.font = [UIFont systemFontOfSize:14];
        cell.labelTitle.text = @"条形码:";
        cell.labelInfo.text =self.barcodeStr;
        return cell;
    }else if (indexPath.section == 1) {
        ZCRaisePicCell*  cell = [[ZCRaisePicCell alloc]initWithStyle:UITableViewCellStyleDefault cellID:@"cell"];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.PicArray  = ImgArray;
        
        cell.picBlock = ^(NSMutableArray *array){
            if (array.count>0) {
                self.footBtn.enabled = YES;
            }else{
                self.footBtn.enabled = NO;
            }
        };
        return cell;

    } else{
        //备注信息
        ZCScanErrorCell *cell =[ZCScanErrorCell tableViewCellScanError:tableView withIndex:indexPath];
        if (indexPath.row ==0) {
            cell.textfiled.text = self.titleStr;
        }
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(valueChanged:) name:UITextFieldTextDidChangeNotification object:cell.textfiled];
        
//        [cell.textfiled addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        return 40;
    }else if (indexPath.section==1){
        return 100;
    }else{
        return 40;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
  
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 60;
    }else{
        return 5;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        ZCSearchHeaderView *head = [[ZCSearchHeaderView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, 60)];
        head.titleLable.font = [UIFont systemFontOfSize:14];
        head.titleLable.text = @"感谢您帮助我们改进！";
        head.titleLable.textColor = [UIColor colorWithHexString:@"#404040"];
        return head;
    }else{
        return nil;
    }
}


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    NSString *tag = [NSString stringWithFormat:@"%ld",textField.tag];
    if (!textField.text) {
        textField.text = @"";
    }
    [self.contentDict setValue:textField.text forKey:tag];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark 值变化

-(void)valueChanged:(NSNotification *)notification{
    
    
    UITextField *textfield=[notification object];

    if ((textfield.tag ==10 && ![textfield.text isEqualToString:self.titleStr])||(textfield.tag ==11 && ![NSString isNull:textfield.text])||(textfield.tag ==12 && ![NSString isNull:textfield.text])) {
        self.footBtn.enabled = YES;
    }else{
        self.footBtn.enabled = NO;
    }
}

#pragma mark - UIGestureRecognizerDelegate Methods

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UITableViewCell class]]) {
        return NO;
    } else {
        return YES;
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark  MessagePhotoViewDelegate

- (void)didSelectePhotoMenuItem:(NSArray *)picArray atIndex:(NSInteger)index{
    ImgArray = [picArray mutableCopy];
    imageCount = ImgArray.count;
    FSMediaPicker *mediaPicker = [[FSMediaPicker alloc] init];
    mediaPicker.delegate = self;
    if (DEVICE_SYSTEM_VERSION) {
        [mediaPicker showFromView:self.view];
    }else{
        [mediaPicker showActionSheet:self.view];
    }
}

- (void)mediaPicker:(FSMediaPicker *)mediaPicker didFinishWithMediaInfo:(NSDictionary *)mediaInfo
{
    NSLog(@"img = %@",mediaInfo.editedImage);
    [ImgArray addObject:mediaInfo.editedImage];
    NSIndexPath *index = [NSIndexPath indexPathForItem:0 inSection:1];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:index] withRowAnimation:UITableViewRowAnimationNone];
    if (ImgArray.count>0) {
        self.footBtn.enabled = YES;
    }else{
        self.footBtn.enabled = NO;
    }
}

#pragma mark 提交

-(void)submitButtonClicks{
    
    if (UserModel.password.length<=1) {
        ZCLoginVC *login = [[ZCLoginVC alloc]init];
        login.hidesBottomBarWhenPushed = YES;
        login.isAd = @"1";
        [self.navigationController pushViewController:login animated:YES];
        return;
    }
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:2];
    ZCScanErrorCell *cellone = [self.tableView cellForRowAtIndexPath:index];
    
    NSString *strname = [NSString stringWithFormat:@"%@",cellone.textfiled.text];
    NSString *strbrand = [NSString stringWithFormat:@"%@",[self.contentDict objectForKey:@"11"]];
    NSString *strspecification = [NSString stringWithFormat:@"%@",[self.contentDict objectForKey:@"12"]];
    if (ImgArray.count>0) {
        NSLog(@"task33");
        [GMDCircleLoader setOnView:self.view withTitle:@"努力加载中..." animated:YES];
        [NetworkManager requestAcsuzhouXwaImageUploadmid:UserModel.mid password:UserModel.password image:ImgArray success:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSString *str = [NSString stringWithFormat:@"%@",[dic objectForKey:@"content"]];
            NSLog(@"上传图片-图片id = %@ ",str);
            
            [NetworkManager requestProductfeedbackProductErrorWithImgid:str name:strname brand:strbrand specification:strspecification mid:UserModel.mid barcode:self.barcodeStr success:^(NSDictionary *dictResponse) {
                [GMDCircleLoader hideFromView:self.view animated:YES];
                NSLog(@"dict = %@",dictResponse);
                
                if (!([dictResponse[@"err"] intValue] == 0))
                {
                    [[[iToast makeText:dictResponse[@"msg"]]setGravity:iToastGravityCenter] show];
                }
                else
                {
                    [[[iToast makeText:dictResponse[@"提交成功"]]setGravity:iToastGravityCenter] show];
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } failure:^(NSError *error) {
                [GMDCircleLoader hideFromView:self.view animated:YES];
                [[[iToast makeText:@"提交出错"]setGravity:iToastGravityCenter] show];
            }];

        } failure:^(NSError *error) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
        }];
    }else{
        [GMDCircleLoader setOnView:self.view withTitle:@"努力加载中..." animated:YES];
        [NetworkManager requestProductfeedbackProductErrorWithImgid:@"" name:strname brand:strbrand specification:strspecification mid:UserModel.mid barcode:self.barcodeStr success:^(NSDictionary *dictResponse) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
            NSLog(@"dict = %@",dictResponse);
            
            if (!([dictResponse[@"err"] intValue] == 0))
            {
                [[[iToast makeText:dictResponse[@"msg"]]setGravity:iToastGravityCenter] show];
            }
            else
            {
                [[[iToast makeText:@"提交成功"]setGravity:iToastGravityCenter] show];
                [self.navigationController popViewControllerAnimated:YES];
            }
        } failure:^(NSError *error) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
            [[[iToast makeText:@"网络出错"]setGravity:iToastGravityCenter] show];
        }];

    }
}

#pragma mark - instance

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = self.viewFooter;
        _tableView.sectionFooterHeight = 0.0001;
        _tableView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
        _tableView.separatorColor = RGB(236, 237, 238);
    }
    return _tableView;
}

- (UIView *)viewFooter {
    if (!_viewFooter) {
        _viewFooter = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
        
        [_viewFooter addSubview:self.footBtn];
        
    }
    return _viewFooter;
}



-(UIButton *)footBtn{
    if (!_footBtn) {
        //提交
        _footBtn = [[UIButton alloc]init];
        _footBtn.layer.cornerRadius = 5;
        _footBtn.layer.masksToBounds = YES;
        _footBtn.enabled = NO;
        [_footBtn setFrame:CGRectMake(20, 50, SCREEN_WIDTH-40, 40)];
//        _footBtn.backgroundColor =[UIColor colorWithHexString:@"#03ab9e"];
        [_footBtn setTitle:@"提交" forState:UIControlStateNormal];
        [_footBtn addTarget:self action:@selector(submitButtonClicks) forControlEvents:UIControlEventTouchUpInside];
        
        [_footBtn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#03ab9e" andAlpha:1]] forState:UIControlStateNormal];
        
        [_footBtn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#03ab9e" andAlpha:0.5]] forState:UIControlStateDisabled];
    }
    return _footBtn;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}




@end
